
#include "Object.h"

	// constructor/destructor
	Object::Object(ObjectName _n) :m_manager(0) ,m_name(_n)
	{

	}
	Object::~Object() 
	{

		// delete all components
		// deleted by the object manager
		/*for (map<string, list<CompPtr> >::iterator it = m_components.begin(); it != m_components.end(); ++it) {
		for (list<CompPtr>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) {
		delete (*it2);
		}
		}*/
	}

	// add a component
	bool Object::AddComponent(const CompPtr& comp) 
	{
		assert(comp);

		m_components[comp->GetId()]=comp;
		return true;
	}

	void Object::DestoryComponent(const CompName& n, const CompId& id)
	{
	}

	ObjectName Object::GetName()
	{
		return m_name;
	}

	// remove a component
	void Object::RemoveComponent(const CompId& id) 
	{

		// look for the right component ant delete it
		CompPtr comp = m_components[id];


		// now we remove all local requests
		for (unsigned i = 0; i < m_localRequests.size(); ++i) 
		{
			/*list<RegisteredComponent>& regs = m_localRequests[i];
			for (list<RegisteredComponent>::iterator it = regs.begin(); it != regs.end();) {
			if (it->component->GetId() == comp->GetId()) {
			it = regs.erase(it);
			}
			else ++it;
			}*/
			/*Vector<RegisteredComponent>& regs = m_localRequests[i];
			for (unsigned j = 0; j < regs.size(); ++j) {
			if (regs[j].component->GetId() == comp->GetId()) {

			}
			}*/
		}
	}

	void Object::ReceiveMessage(const ComponentRequest& req, const Message& msg) 
	{

		// if there are no registered components, we just skip
		if (m_localRequests[req.type][req.id].empty()) return;

		// just forward to the appropriate registered components
		CallbackList cb = m_localRequests[req.type][req.id];
		for(CallbackList::iterator iter=cb.begin();iter!=cb.end();iter++)
		{
			if(iter->cid!=msg.sender)
				iter->callback(msg);
		}
		
	}

	// register a request
	void Object::RegisterRequest(const ComponentRequest& req, const RegisteredComponent& reg) 
	{
		// TODO OPTIMIZATION
		m_localRequests[req.type][req.id].push_back(reg);
	}

	void Object::RegisterComponent(const ComponentRequest& req, const RegisteredComponent& reg)
	{
	
		for(CompMap::iterator iter=m_components.begin();iter!=m_components.end();iter++)
		{
			if(iter->second->GetName()==req.id.comp)
			{
				reg.callback(MSG_COMP(iter->second->GetId(),iter->second));
			}
		}
	}
	
#ifdef _DEBUG
	stringstream Object::Dump()
	{
		return stringstream("");
	}
#endif
